<?php
require "Base64.class.php";
/**
 * 反向代理Cookie操作
 *
 * How it works
 *
 *   --->   ---> 
 * C      P      S
 *   <---   <---
 *
 * S -> P Set-Cookie: BAIDUID=2DD778194EEA0CFEC6BEDAE9ECDA74FC:FG=1; expires=Tue, 03-Jan-42 07:52:16 GMT; path=/; domain=.baidu.com
 * P -> C Cookie转换算法:
 *        Set-Cookie: BASE64(".baidu.com".","."/".","."BAIDUID") = BASE64("BAIDUID=2DD778194EEA0CFEC6BEDAE9ECDA74FC:FG=1;");expires=Tue, 03-Jan-42 07:52:16 GMT; path=/;
 *
 * C -> P Cookie: key1 = value1; key2 = value2; key3 = value3; 
 *        URL: http://www.example.com/path
 *
 * P -> S Cookie转换算法:
 *        foreach ($cookies as $cookie_key => $cookie_value) {
 *            $cookie_path_domain = BASE64_DECODE($cookie_key);
 *            $cookie_value = BASE64_DECODE($cookie_value);
 *            if ($cookie_path_domain.matched($request_url)) {
 *                #发送Cookie
 *                Cookie:$cookie_value
 *            }
 *        }
 */
class CookieEncoder {

	private $_cookies;
	private $_encoded_cookie;

	public function __construct($cookies,$url) {

		if (is_string($cookies)) {
		    $this->_cookies[] = $cookies;
		} else {
		    $this->_cookies = $cookies;
		}

        $parsed_url = parse_url($url);
		if (!array_key_exists('path',$parsed_url)) {
			$parsed_url['path'] = '/';
		}
		foreach($this->_cookies as $raw_cookie_str) {
			$this->_encoded_cookie[] = $this->encodeCookie($raw_cookie_str,$parsed_url["host"],$parsed_url["path"]);
		}
	}

	public function getEncodedCookie() {
		return $this->_encoded_cookie;
	}

	private function encodeCookie($cookie_str,$default_actual_cookie_domain,$default_actual_cookie_path) {
		$cookie_parts = explode("; ",trim($cookie_str));
		$new_cookie_parts = array();
		$actual_cookie_domain = $default_actual_cookie_domain;
		$actual_cookie_path = $default_actual_cookie_path;
		$cookie_expires = "";// 透传cookie过期时间
		$new_cookie_str = '';
		$new_cookie_keys = array();
		foreach($cookie_parts as $cookie_part) {
			$t_parts = explode("=",$cookie_part);
			$t_parts[0] = strtolower(trim($t_parts[0]));
			if($t_parts[0] == "domain") {
				$actual_cookie_domain = trim($t_parts[1]);// 键名第一部分cookie所属域
			} else if($t_parts[0] == "path") {
				$actual_cookie_path = trim($t_parts[1]); // 键名第二部分cookie所属路径
			} else if($t_parts[0] == "expires"){
				$cookie_expires = trim($t_parts[1]);// 透传cookie过期时间
			} else {
				$new_cookie_keys[] = $t_parts[0]; // 确保相同的key只产生同一个cookie key
				$new_cookie_parts[] = $cookie_part;
			}
		}
		$actual_cookie_path = pathinfo($actual_cookie_path);
		// 替换base64中的=为_以避免与cookie中的等号混淆
		$new_cookie_str .= Base64::encode($actual_cookie_domain.",".$actual_cookie_path["dirname"].",".implode(";",$new_cookie_keys));
		$new_cookie_str .= "=";
		$new_cookie_str .= Base64::encode(implode("; ",$new_cookie_parts));
		if (!empty($cookie_expires)) {
		    $new_cookie_str .= "; expires=".$cookie_expires;
		}
		$new_cookie_str .= "; path=/";
		return $new_cookie_str;
	}

}
